package com.tao.controller;

import com.github.pagehelper.Page;
import com.tao.pojo.Brand;
import com.tao.pojo.BrandExample;
import com.tao.pojo.BrandExample.Criteria;
import com.tao.service.brand.BrandServiceImpl;
import com.tao.util.MyFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/brand")
public class BrandController {
	
	@Autowired
	BrandServiceImpl brandService;
	
	@RequestMapping("/show.do")
	public String brandShow(Brand brand,ModelMap map) {
		BrandExample example=new BrandExample();
		example.setOrderByClause("id desc");
		StringBuilder params=new StringBuilder();
		Criteria createCriteria = example.createCriteria();
		if(StringUtils.isNotBlank(brand.getName()) ){
			createCriteria.andNameLike("%"+brand.getName().trim()+"%");
			params.append("&name="+brand.getName().trim());
		}
		if(brand.getIsDel()!=null){
			createCriteria.andIsDelEqualTo(brand.getIsDel());
			System.out.println(brand.getIsDel());
			params.append("&isDel="+brand.getIsDel()); 
		}
		Page<Brand> brands=(Page<Brand>) brandService.query(brand, example);
		
		brand.setImgUrl("show.do");
		brand.setPages(brands.getPages());
		brand.setParams(params.toString());
		map.addAttribute("brands", brands);
		map.addAttribute("brand", brand); //防止页面刷新后，查询条件失效
		return "brand/show";
	}	
	
	@RequestMapping(value="/add.do",method=RequestMethod.GET)
	public String goAdd() {
		return "brand/add";
	}

	@RequestMapping(value="/add.do",method=RequestMethod.POST)
	public String doAdd(Brand brand,MultipartFile logoImg) {
		//new upload
		String fileName = MyFileUtils.upload(logoImg);
		//----写入数据库---
		brand.setImgUrl(fileName);
		brandService.add(brand);
		return  "redirect:show.do";
	}
	/**
	 * 删除和撤销删除
	 * @param id
	 * @param flag 0：删除 1：撤销删除
	 * @return
	 */
	@RequestMapping("/del")
	public String delete(Integer id,Integer flag) {
		if(flag==0) {
			brandService.del(id);
		}else if(flag==1) {
			brandService.undel(id);
		}
		return "redirect:show.do";
	}
	
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public String goUpdate(Integer id,ModelMap map) {
		Brand brand = brandService.getBrandById(id);
		map.addAttribute("brand", brand);
		return "brand/update";
	}
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String doUpdate(Brand brand,MultipartFile file) {
		if(!"".equals(file.getOriginalFilename())) { //更新了图片
			String fileName = MyFileUtils.upload(file);
			brand.setImgUrl(fileName);
		}else {//没有更新图片
			//do nothing
		}
		brandService.update(brand);
		return "redirect:show.do";
	}
}
